$(function(){
    if($.validator){
        $.validator.setDefaults({
            submitHandler: function (form) {
                var fileDoms = $(form).find('[data-role="upload"]:visible');
                var flag = false;
                fileDoms.each(function(index,dom){
                var data_content=$(dom).attr("data-content");
                var dataJson=eval("("+data_content+")")
                    if(!$(dom).hasClass("not-required")){
                        if($(dom).find(".weui-uploader__file").length == 0 && dataJson.sfbx!=0){
                            if(!flag){
                                var scrollTop = $(dom).offset().top;
                                $('html,body').animate({scrollTop: scrollTop}, function(){
                                    if($(dom).find('.errorTips:visible').length == 0){
                                        $(dom).find('input[type=file]').click();
                                        var $html = $('<div style="color: red"></div>').addClass('weui-cells__tips red errorTips').append(
                                            '<i class="weui-icon-warn" style="font-size: 0.7rem;"></i>'
                                        ).append('请上传')
                                            .append(
                                                '相关材料证件照片'//$(dom).find('.weui-cells__title').html()
                                            );
                                        $(dom).append($html);
                                    }
                                });
                            }else{
                                var $html = $('<div  style="color: red"></div>').addClass('weui-cells__tips red errorTips').append(
                                    '<i class="weui-icon-warn" style="font-size: 0.7rem;"></i>'
                                ).append('请上传')
                                    .append(
                                    		'相关材料证件照片'//$(dom).find('.weui-cells__title').html()
                                    );
                                $(dom).append($html);
                            }
                            flag = true;
                            return true;
                        }
                    }
                });
                if(flag){
                    return false;
                }

                if ($('[data-role="childs"]:visible').length > 0) {
                    var childsflag = false;
                    $('[data-role="childs"]:visible').each(function(index, dom){
                        var $dom = $(this)
                            ,title = $dom.siblings('.weui-panel__hd').text()
                            ,$childs = $dom.find('.child')
                        ;
                        if(!title){
                        	title = $dom.parents('.weui-panel__bd').prev('.weui-panel__hd').text();
						}
                        if($childs.length == 0){
                            $dom.addClass("has-error");
                            $.alert('请填写' + title)
                            childsflag = true;
                        }
                    });
                    if(childsflag){
                        return false;
                    }
                }

                // 验签
                signature();
                // subForm($(form));
            }
        });

        $('[data-role="form"]').each(function(index, dom){
            $(dom).validate({
                showErrors:function(errorMap,errorList) {
                    this.defaultShowErrors();
                },
                errorPlacement: function(error, element) {
                    var $panel = element.parents('.weui-cells:first');
                    if($panel.find('.weui-cell').length > 1||$panel.find('.cuiui-cell').length > 1){
                        $.toptip($(error), 'error');
                        element.parents('.weui-cell').addClass("weui-cell_warn");
                        element.parents('.cuiui-cell').addClass("weui-cell_warn");
                       /* element.parents('.weui-cell:first').after('<div class="weui-cell__ft">'+
                            '<i class="weui-icon-warn"></i>'+
                            '</div>');*/
                    }else{
                        $panel.after($(error));
                    }
                }
            });
        });

        $('[data-role="form"]').delegate('.weui-cell_warn input,.weui-cell_warn textarea', 'click', function(){
        	$(this).parents('.weui-cell_warn:first').removeClass('weui-cell_warn');
		}).delegate('.weui-cell_warn input,.weui-cell_warn textarea', 'change', function(){
            $(this).parents('.weui-cell_warn:first').removeClass('weui-cell_warn');
        })
    }

    //签名方法
    function signature(){
		var $signatureWrapper = $('#signatureWrapper');
		if($signatureWrapper.length == 0){
            var signatureUrl = getRootPath() + '/toSignature?_='+ Math.random();
            var $iframe = $('<iframe frameborder="0" width="100%" height="100%"></iframe>').attr('src', signatureUrl);

            var $bar = $('<div></div>').addClass('toolbar').append(
                '<div class="toolbar-inner"><a href="javascript:;" class="picker-button close-popup">关闭</a><h1 class="title">请填写签名</h1></div>'
            );

            var $signatureHtml = $('<div></div>').addClass('weui-popup__container').attr('id', 'signatureWrapper')
                .append(
                    $('<div></div>').addClass('weui-popup__modal').append($bar).append(
                        $('<div style="height: 100%;"></div>').addClass('weui-modal-content').append($iframe)
					)
                );

            $('body').append($signatureHtml);
        }else{
            $('#signatureWrapper').find('iframe').attr('src', $('#signatureWrapper').find('iframe').attr('src'));
		}
        $('#signatureWrapper').popup();
	}
});

function sumitISignatureImageFile(base64Codes) {

    var convertBase64UrlToBlob = function (urlData) {
        var arr = urlData.split(',');
        var mime = arr[0].match(/:(.*?);/)[1];
        var bytes = window.atob(urlData.split(',')[1]);        //去掉url的头，并转换为byte

        //处理异常,将ascii码小于0的转换为大于0
        var ab = new ArrayBuffer(bytes.length);
        var ia = new Uint8Array(ab);
        for (var i = 0; i < bytes.length; i++) {
            ia[i] = bytes.charCodeAt(i);
        }

        return new Blob([ab], { type: mime });
    };

    var getFileExt = function (urlData) {
        var arr = urlData.split(',');
        var mime = arr[0].match(/:(.*?);/)[1];
        return mime.replace("image/", "");
    };

    var form = $('[data-role="form"]:first');

    //var formData = new FormData(form);   //这里连带form里的其他参数也一起提交了,如果不需要提交其他参数可以直接FormData无参数的构造函数
    var formData = new FormData();

    var fileExt = getFileExt(base64Codes);

    //convertBase64UrlToBlob函数是将base64编码转换为Blob
    formData.append("file", convertBase64UrlToBlob(base64Codes), "file_" + Date.parse(new Date()) + "." + fileExt);  //append函数的第一个参数是后台获取数据的参数名,和html标签的input的name属性功能相同
    formData.append('tableName', 'SIGNATURE');
    //ajax 提交form
    var url = getRootPath()+'/wfw/spyxmp/file/uploadSignature';
    $.ajax({
        url: url,
        type: "POST",
        data: formData,
        //dataType: "text",
        processData: false,         // 告诉jQuery不要去处理发送的数据
        contentType: false,        // 告诉jQuery不要去设置Content-Type请求头
        beforeSend : function() {
            $.showLoading();
        },
        success: function (response) {
            $.hideLoading();
            if(response.success){
				subForm(form);
			}else{
                $.toast("签名失败", "forbidden");
			}
        }
    });
}

function FormatDate(strTime) {
	var date = new Date(strTime);
	return date.getFullYear() + "年" + (date.getMonth() + 1) + "月"
			+ date.getDate() + "日";
}
function toHref(href){
    $.showLoading();
    window.location.href = href;
}

function checkboxToVal(data){
	var result = data.checked?"1":"0";
	$("#"+data.id+"-val").val(result);
}

function checkIdCard(idcardObj) {
	var zjlx = $("select[name='cardType']").find("option:selected").val();
	if (zjlx == "10") {
		var Errors = new Array("ok", "身份证号码位数不对! ",
				"身份证号码出生日期超出范围或含有非法字符! ", "您输入的身份证号码有误! ", "身份证地区非法! ",
				"未满6周岁不能参与申报!");
		var area = {
			11 : "北京",
			12 : "天津",
			13 : "河北",
			14 : "山西",
			15 : "内蒙古",
			21 : "辽宁",
			22 : "吉林",
			23 : "黑龙江",
			31 : "上海",
			32 : "江苏",
			33 : "浙江",
			34 : "安徽",
			35 : "福建",
			36 : "江西",
			37 : "山东",
			41 : "河南",
			42 : "湖北",
			43 : "湖南",
			44 : "广东",
			45 : "广西",
			46 : "海南",
			50 : "重庆",
			51 : "四川",
			52 : "贵州",
			53 : "云南",
			54 : "西藏",
			61 : "陕西",
			62 : "甘肃",
			63 : "青海",
			64 : "宁夏",
			65 : "新疆",
			71 : "台湾",
			81 : "香港",
			82 : "澳门",
			91 : "国外"
		};
		var error = "";
		var idcard = idcardObj.value;
		var Y, JYM;
		var S, M;
		var idcard_array = new Array();
		idcard_array = idcard.split("");

		//身份号码位数及格式检验 
		if (idcard.length == 18) {
			//18位身份号码检测 
			//出生日期的合法性检查  
			//闰年月日:((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9])) 
			//平年月日:((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8])) 
			if (parseInt(idcard.substr(6, 4)) % 4 == 0
					|| (parseInt(idcard.substr(6, 4)) % 100 == 0 && parseInt(idcard
							.substr(6, 4)) % 4 == 0)) {
				ereg = /^[1-9][0-9]{5}[1-2][(0|9)][0-9][0-9]((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$/;//闰年出生日期的合法性正则表达式 
			} else {
				ereg = /^[1-9][0-9]{5}[1-2][(0|9)][0-9][0-9]((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$/;//平年出生日期的合法性正则表达式 
			}
			if (ereg.test(idcard)) {//测试出生日期的合法性 
				//计算校验位 
				S = (parseInt(idcard_array[0]) + parseInt(idcard_array[10]))
						* 7
						+ (parseInt(idcard_array[1]) + parseInt(idcard_array[11]))
						* 9
						+ (parseInt(idcard_array[2]) + parseInt(idcard_array[12]))
						* 10
						+ (parseInt(idcard_array[3]) + parseInt(idcard_array[13]))
						* 5
						+ (parseInt(idcard_array[4]) + parseInt(idcard_array[14]))
						* 8
						+ (parseInt(idcard_array[5]) + parseInt(idcard_array[15]))
						* 4
						+ (parseInt(idcard_array[6]) + parseInt(idcard_array[16]))
						* 2
						+ parseInt(idcard_array[7])
						* 1
						+ parseInt(idcard_array[8])
						* 6
						+ parseInt(idcard_array[9]) * 3;
				Y = S % 11;
				M = "F";
				JYM = "10X98765432";
				M = JYM.substr(Y, 1);//判断校验位
				//地区检验 
				if (area[parseInt(idcard.substr(0, 2))] == null) {
					error = Errors[4];
					$.alert(error);
					idcardObj.value = "";
					idcardObj.focus();
					return false;
				}
				if (M == idcard_array[17]) {
					var flag = true;
					var currentYear = new Date().getFullYear();
					var brithyear = idcard.substr(6, 4);
					var brithmon = idcard.substr(10, 2);
					if (currentYear - 6 == brithyear) {
						if (parseInt(brithmon) >= 9) {
							flag = false;
						}
					} else {
						flag = currentYear - brithyear > 6;
					}
					if (!flag) {//年龄要大于6岁
						error = Errors[5];
						$.alert(error);
						idcardObj.value = "";
						idcardObj.focus();
						return false;
					}
					return true;
				} else {
					error = Errors[3];
					$.alert(error);
					idcardObj.value = "";
					idcardObj.focus();
					return false;
				}
			} else {
				error = Errors[2];
				$.alert(error);
				idcardObj.value = "";
				idcardObj.focus();
				return false;
			}

		} else {
			error = Errors[1];
			$.alert(error);
			idcardObj.value = "";
			idcardObj.focus();
			return false;
		}
	} else if (zjlx == "11") {
		//港澳通行证验证
		var re = /^(MAG0|MAC0|HKG0|M)[0-9]{8,9}$/;
		var idcard = idcardObj.value;
		if (idcard.length == 9||idcard.length == 12||idcard.length == 13) {
			if (re.test(idcard)) {
				return true;
			} else {
				$.alert("港澳通行证格式不正确！");
				idcardObj.value = "";
				idcardObj.focus();
				return false;
			}
		}else{
			$.alert("港澳通行证位数错误!");
			idcardObj.value = "";
			idcardObj.focus();
			return false;
		}
	}
}

function ajaxInfo(para) {
	var data;
	var successfn = para.successfn || function(response, textStatus, XMLHttpRequest){
		if(response && response.success) {
            data = response.data;
            return data;
		} else {
			//var msg = response.msg ? response.msg : result.error;
        	//ZENG.msgbox.show('',{icon:5});
		}
	}
	$.ajax({
		url : para.url,
		type : para.type || 'post',
		async : para.async || false,
		dataType : para.dataType || 'JSONP',
		data: para.data,
		jsonpCallback : para.jsonCallback || 'callback',
		contentType : "application/x-www-form-urlencoded;charset=UTF-8",
		beforeSend : function() {
			$.showLoading();

		},
		success : successfn ,
		error : function() {
			$.hideLoading();
			$.toast("程序异常请重试", "forbidden");
		},complete: function(){
        }
	});
	return data;

}




/**
 * 获取当前登录用户信息
 */
function funGetUser(){
    var openId = $('#openId').val()
        ,url = getRootPath() + "/wfw/getSuser?"+Math.random();
    var user = getDataFn({url:url, data:{openId: openId}});
    return user;
}

function subForm(obj) {

	var $subForm = $(obj);

	$.ajax({
		// 几个参数需要注意一下
		type : "POST",// 方法类型
		dataType : 'JSON',
		url : $subForm.attr("action"),// url
		data : $subForm.serialize(),
		beforeSend : function() {
			$.showLoading();
		},
		success : function(response) {
			$.hideLoading();
			if (response.success) {
				if(response.data!=null){
                    $("#id").val(response.data.id);
				}

				$.toast(response.msg, function(){
					if($subForm.attr('next_url')){
                        location.href = $subForm.attr('next_url');
					}
				    if(!$subForm.data('fixed')){
				        if($subForm.attr('data-refer-href')){
                            location.href = $subForm.attr('data-refer-href');
                        }else if($subForm.find('.btn-reply').length > 0){
                            $subForm.find('.btn-reply').click();
						}else if(response.toUrl){
                            location.href = getRootPath() + response.toUrl;
                        }else{
                            location.href = getRootPath() + '/toSuccess?sblsh=' + response.data.sblsh || response.data.SBLSH;
                        }
                    }
				});
			} else {
				$.toast(response.msg || "数据保存失败请重试", "forbidden");
			}
			;
		},
		error : function() {
			$.hideLoading();
			$.toast("程序异常请重试", "forbidden");
		}
	});
};


/**
 * 获取项目根路径
 * @returns
 */
function getRootPath(){
    //获取当前网址，如： http://localhost:8083/uimcardprj/share/meun.jsp
    var curWwwPath=window.document.location.href;
    //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
    var pathName=window.document.location.pathname;
    var pos=curWwwPath.indexOf(pathName);
    //获取主机地址，如： http://localhost:8083
    var localhostPaht=curWwwPath.substring(0,pos);
    //获取带"/"的项目名，如：/uimcardprj
    var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
    return(localhostPaht+projectName);
}

function callback(json){
}

function lastStep(step) {
    location.href=getRootPath()+"/toIndex?step="+step;
}
